package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import modelo.Fluido;

public class FluidoDao {
	
	private Connection conexao;
	
	public FluidoDao(Connection con) throws ClassNotFoundException {
		this.conexao = con;		
	}
	
	public Fluido getFluido(int codigo) {		
		Fluido fluido = null;		
		PreparedStatement stm = null;
		try {
			stm = conexao.prepareStatement("select * from fluido " +  
										   "where codigo = ?");
			stm.setInt(1, codigo);			
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				fluido = this.setDados(rs);
			}
			stm.close();
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return fluido;		
	}
	
	public Fluido getFluido(String nome) {		
		Fluido fluido = null;		
		PreparedStatement stm = null;
		try {
			stm = conexao.prepareStatement("select * from fluido " +  
										   "where nome = ?");
			stm.setString(1, nome);			
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				fluido = this.setDados(rs);
			}
			stm.close();
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return fluido;		
	}
	
	public int getCodigoFluido(String fluido) {		
		int codigo = 0;		
		PreparedStatement stm = null;
		try {
			stm = conexao.prepareStatement("select * from fluido " +  
										   "where nome = ?");
			stm.setString(1, fluido);			
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				codigo = rs.getInt("codigo");
			}
			stm.close();
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return codigo;		
	}
	
	public List<String> getFluido() {		
		String f = null;		
		PreparedStatement stm = null;
		List<String> listaFluidos = null;
		try {
			stm = conexao.prepareStatement("select * from fluido");						
			ResultSet rs = stm.executeQuery();
			while (rs.next()) {
				f = rs.getString("nome");
				if(!(f == null) ) {
					if(listaFluidos == null) {
						listaFluidos = new ArrayList<String>();
					}
				listaFluidos.add(f);
				}				
			}
			stm.close();
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		}
		return listaFluidos;		
	}
	
	private Fluido setDados(ResultSet rs) throws SQLException {
		Fluido fluido = new Fluido();
		fluido.setCdFluido(rs.getInt("codigo"));
		fluido.setDsFluido(rs.getString("nome"));
		return fluido;
	}

}
